package com.ruoyi.common.utils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 简历格式化处理类
 * TYF 2022 10 29
 */
public class ResumeUtil {

    public Result checkJianLi(String jianli) {
        if (StringUtils.isBlank(jianli)) {
            return Result.fail("该简历为空！");
        }
        jianli = jianli.replaceAll("\\\\n", "\r").replaceAll("\\\\r", "\r").replaceAll("\n", "\r");
        jianli = dealJianliTextPutOffSpecial(jianli);
        List<Map<String, String>> list = getA1701List(jianli);
        Result res = checkJianLi(list);
        if (res.isSuccess()) {
            res.setObj(list);
        }
        return res;
    }


    /**
     * 切割简历
     * @param jianli
     * @return
     */
    public List<Map<String, String>> splitJianLi(String jianli) {
        //如果有空格 则替换为换行
        jianli = jianli.replaceAll("\\\\n", "\r").replaceAll("\\\\r", "\r").replaceAll("\n", "\r");
        jianli = dealJianliTextPutOffSpecial(jianli);
        List<Map<String, String>> list = getA1701List(jianli);
        return list;
    }

    /**
     * 格式化 返回集合
     * @param a1701
     * @return
     */
    private List<Map<String, String>> getA1701List(String a1701) {
        if (StringUtils.isBlank(a1701)) {
            return new ArrayList<>();
        }
        //切割
        String[] st = a1701.split("\r");
        List<Map<String, String>> listMap = new ArrayList<>();
        String[] sts = null;
        List<Integer> listInt = null;
        for (int j = 0; j < st.length; j++) {
            String str = st[j];
            Map<String, String> map = new HashMap<>();
            String string = "";
            str = str.trim().replaceAll("&nbsp;", " ").replaceAll("　　　　", " ");
            if (j == st.length - 1 &&
                    sts != null ) {
                map.put("key", "");
                map.put("value", str);
                listMap.add(map);
            }
            else {

                sts = str.split(" ");
                if (sts.length > 0) {

                    map.put("key", sts[0]);
                    if (sts.length > 1) {
                        for (int i = 1; i < sts.length; i++) {
                            String newStr = "";
                            if (StringUtils.isNotBlank(sts[i])) {
                                listInt = new ArrayList<>();
                                listInt = getSpecialSignIndexArray(sts[i], "（", 0, listInt);
                                listInt = getSpecialSignIndexArray(sts[i], "(", 0, listInt);
                                Collections.sort(listInt);
                                newStr = dealJianliSpecialPartToCheck(sts[i], listInt);
                                string = string + newStr;
                            }
                        }


                        map.put("value", string);
                    } else {
                        map.put("value", string);
                    }
                    listMap.add(map);
                }
            }
        }
        return listMap;
    }

    public static List<Integer> getSpecialSignIndexArray(String str, String sign, int fromIndex, List<Integer> list) {
        int index = str.indexOf(sign, fromIndex);
        if (index != -1) {
            list.add(Integer.valueOf(index));
            return getSpecialSignIndexArray(str, sign, index + 1, list);
        }
        return list;
    }


    public static String dealJianliSpecialPartToShow(String str, List<Integer> list) {
        Pattern pattern = Pattern.compile("\\（\\d{4}\\.\\d{1,2}");
        Pattern pattern1 = Pattern.compile("\\(\\d{4}\\.\\d{1,2}");
        StringBuffer sb = new StringBuffer(str);
        for (int i = list.size() - 1; i >= 0; i--) {
            int in = ((Integer)list.get(i)).intValue();
            if (str.substring(in).length() >= 10 &&
                    "--".equals(str.substring(in + 8, in + 10)) && (pattern.matcher(str.substring(in, in + 8) + "").matches() || pattern1.matcher(str.substring(in, in + 8) + "").matches())) {
                sb.insert(in, "<br/>");
                sb.append("  ");
            }
        }

        return sb.toString();
    }






    private String dealJianliSpecialPartToCheck(String str, List<Integer> list) {
        StringBuffer sb = new StringBuffer(str);
        for (int i = list.size() - 1; i >= 0; i--) {
            int in = ((Integer)list.get(i)).intValue();
            sb.insert(in, "<br/>");
            sb.append("  ");
        }
        return sb.toString();
    }



    public static boolean isHaveString(String str) {
        if (str.indexOf("中央委员") != -1)
            return true;
        if (str.indexOf("候补委员") != -1)
            return true;
        if (str.indexOf("中央纪委委员") != -1)
            return true;
        if (str.indexOf("全国人大常委会委员") != -1)
            return true;
        if (str.indexOf("全国政协常务委员") != -1)
            return true;
        if (str.indexOf("人大代表") != -1) {
            return true;
        }
        return false;
    }






    public static String dealJianliText(String a1701) {
        Pattern pattern = Pattern.compile("\\d{4}\\.\\d{1,2}");
        Matcher isNum = null;
        String[] st = a1701.replaceAll("\\\\n", "\r").replaceAll("\\\\r", "\r").replaceAll("\n", "\r").split("\r");

        List<String> list = new ArrayList<>();
        for (String str : st) {
            if (StringUtils.isNotBlank(str.trim())) {
                list.add(str.trim());
            }
        }
        String newStr = "";
        if (list.size() == 1) {
            newStr = list.get(0);
            return newStr;
        }
        for (int i = 0; i < list.size(); i++) {
            String str = list.get(i);
            String[] s = str.split(" ");
            if (i != list.size() - 1) {
                if (s[0].length() >= 7) {
                    isNum = pattern.matcher(str.substring(0, 7) + "");
                    if (isNum.matches()) {
                        if (StringUtils.isBlank(newStr)) {
                            newStr = newStr + str;
                        }
                        else if (s[0].length() > 16) {
                            newStr = newStr + ";" + str;
                        } else {
                            newStr = newStr + "\r" + str;
                        }
                    } else {

                        newStr = newStr + str;
                    }
                } else {
                    newStr = newStr + str;
                }

            }
            else if (str.length() >= 7) {
                isNum = pattern.matcher(str.substring(0, 7) + "");
                if (isNum.matches()) {
                    newStr = newStr + "\r" + str;
                } else {
                    newStr = newStr + str;
                }
            } else {
                newStr = newStr + str;
            }
        }


        return newStr;
    }





    private String dealJianliTextPutOffSpecial(String a1701) {
        Pattern pattern = Pattern.compile("\\d{4}\\.\\d{1,2}");
        Matcher isNum = null;
        String[] st = a1701.replaceAll("\\\\n", "\r").replaceAll("\\\\r", "\r").replaceAll("\n", "\r").split("\r");

        List<String> list = new ArrayList<>();
        for (String str : st) {
            if (StringUtils.isNotBlank(str.trim())) {
                list.add(str.trim());
            }
        }
        String newStr = "";
        for (int i = 0; i < list.size(); i++) {
            String str = list.get(i);
            if (i != list.size() - 1) {
                if (str.length() >= 7) {
                    isNum = pattern.matcher(str.substring(0, 7) + "");
                    if (isNum.matches()) {
                        if (StringUtils.isBlank(newStr)) {
                            newStr = newStr + str;
                        } else {
                            newStr = newStr + "\r" + str;
                        }
                    } else {
                        newStr = newStr + str;
                    }
                } else {
                    newStr = newStr + str;
                }

            }
            else if (str.length() >= 7) {
                isNum = pattern.matcher(str.substring(0, 7) + "");
                if (isNum.matches()) {
                    newStr = newStr + "\r" + str;
                }
                else {
                    newStr = newStr + str;
                }
            } else {

                newStr = newStr + str;
            }
        }


        return newStr;
    }





    private Result checkJianLi(List<Map<String, String>> listmap) {
        Result res = null;
        Map<String, Object> mapTemp = null;
        List<Map<String, Object>> list = new ArrayList<>();
        String lastStart = null;
        String lastEnd = null;
        Date lastStartDate = null;
        Date lastEndDate = null;
        for (Map<String, String> temp : listmap) {
            String key = temp.get("key");
            String value = temp.get("value");
            if (StringUtils.isBlank(key) && StringUtils.isBlank(value)) {
                continue;
            }
            mapTemp = new HashMap<>();
            mapTemp.put("key", key);
            mapTemp.put("value", value);
            list.add(mapTemp);
        }

        for (int i = 0; i < list.size(); i++) {
            mapTemp = list.get(i);
            if (i == 0) {
                mapTemp.put("isFirst", Boolean.valueOf(true));
            }
            String key = (String)mapTemp.get("key");
            String value = (String)mapTemp.get("value");
            String start = "";

            if (StringUtils.isNotBlank(key) && !key.trim().equals("--") && key.indexOf("--") != -1) {
                String[] arg = key.split("--");
                if (StringUtils.isNotBlank(arg[0])) {
                    res = checkDateString(arg[0]);
                    if (!res.isSuccess()) {
                        return res;
                    }
                    res = parse(arg[0]);
                    if (!res.isSuccess()) {
                        return res;
                    }
                    mapTemp.put("start", arg[0]);
                    mapTemp.put("startDate", res.getObj());
                    mapTemp.put("lastStartDate", lastStartDate);
                    mapTemp.put("lastStart", lastStart);
                    start = arg[0];


                    if (i != 0 &&
                            !start.equals(lastEnd)) {
                        return Result.fail("“" + key + "”的开始年.月需要和上一条简历中结束年.月相同！");
                    }


                    lastStart = arg[0];
                    lastStartDate = (Date)res.getObj();
                } else {

                    return Result.fail("该简历中”" + key + "“的日期格式有问题！");
                }
                if (arg.length >= 2 && StringUtils.isNotBlank(arg[1])) {
                    res = checkDateString(arg[1]);
                    if (!res.isSuccess()) {
                        return res;
                    }
                    res = parse(arg[1]);
                    if (!res.isSuccess()) {
                        return res;
                    }
                    mapTemp.put("end", arg[1]);
                    mapTemp.put("endDate", res.getObj());
                    mapTemp.put("lastEnd", lastEnd);
                    mapTemp.put("lastEndDate", lastEndDate);
                    lastEnd = arg[1];
                    lastEndDate = (Date)res.getObj();
                } else {

                    mapTemp.put("lastEnd", lastEnd);
                    mapTemp.put("lastEndDate", lastEndDate);
                    lastEnd = "";
                    lastEndDate = null;
                }
            } else {
                return Result.fail("该简历中的“" + key + "”时间格式有问题！");
            }
            if (StringUtils.isNotBlank(value)) {
                if (i == list.size() - 1) {
                    mapTemp.put("isLast", Boolean.valueOf(true));
                }
                res = checkValue(value, mapTemp);
                if (!res.isSuccess()) {
                    return res;
                }
            } else {
                return Result.fail("该简历中“" + key + "”后边没有职务信息！");
            }
        }
        return Result.ok();
    }
    private Result checkValue(String value, Map<String, Object> map) {
        boolean isFirst = (map.get("isFirst") == null) ? false : ((Boolean)map.get("isFirst")).booleanValue();
        boolean isLast = (map.get("isLast") == null) ? false : ((Boolean)map.get("isLast")).booleanValue();

        String start = (String)map.get("start");
        String end = (String)map.get("end");
        Date startDate = (Date)map.get("startDate");
        Date endDate = (map.get("endDate") == null) ? null : (Date)map.get("endDate");
        Date lastStartDate = (Date)map.get("lastStartDate");
        Date lastEndDate = (map.get("lastEndDate") == null) ? null : (Date)map.get("lastEndDate");

        if (isLast && endDate == null) {
            endDate = new Date();
            end = DateUtils.formatDate(endDate, new Object[] { "yyyy.MM" });
        }
        if (!isLast && (
                startDate == null || endDate == null)) {
            String key = (map.get("key") == null) ? "" : String.valueOf(map.get("key"));
            return new Result(false, "该简历中”" + key + "  " + value + "“的起始日期或者结束日期为空！");
        }


        Pattern pattern = Pattern.compile("\\d{1}");
        Matcher isNum = null;
        String[] strs = value.split("<br/>");
        Result res = null;
        for (String str : strs) {
            if (StringUtils.isNotBlank(str) && (str.startsWith("(") || str.startsWith("（"))) {
                String val = str.substring(1);

                if (val.startsWith("期间") || val.startsWith("其间")) {
                    if (val.startsWith("期间：") || val.startsWith("期间:") || val.startsWith("其间：") || val.startsWith("其间:")) {
                        val = val.replace("期间：", "").replace("期间:", "").replace("其间：", "").replace("其间:", "");
                        res = checkDateStr(value.replace("<br/>", ""), val, startDate, endDate, lastStartDate, lastEndDate, true, isFirst, isLast);
                        if (!res.isSuccess()) {
                            return res;
                        }
                    } else {
                        return new Result(false, "该简历中”" + str + "“的“期间”或者“其间”后的格式不正确！");
                    }

                }
                else if (!StringUtils.isBlank(str)) {


                    String tempV = str.substring(0, 1);
                    isNum = pattern.matcher(tempV);
                    if (isNum.matches()) {



                        if (isFirst) {
                            res = checkDateStr(value.replace("<br/>", ""), val, startDate, endDate, lastStartDate, lastEndDate, true, isFirst, isLast);
                        } else {
                            res = checkDateStr(value.replace("<br/>", ""), val, startDate, endDate, lastStartDate, lastEndDate, false, isFirst, isLast);
                        }
                        if (!res.isSuccess()) {
                            return res;
                        }
                    }
                }
            }
        }

        return Result.ok();
    }











    private Result checkDateStr(String oriValue, String value, Date start, Date end, Date lastStart, Date lastEnd, boolean isQJ, boolean isFirst, boolean isLast) {
        Pattern pattern = Pattern.compile("\\d{4}\\.\\d{2}--\\d{4}\\.\\d{2}");
        Pattern pattern1 = Pattern.compile("\\d{4}\\.\\d{2}");
        Matcher isNum = null;
        Result res = null;
        if (null == lastEnd && !isFirst) {
            return Result.fail("“" + oriValue + "”上一条简历中开始年.月为空！");
        }
        Date qjStart = null;
        Date qjEnd = null;
        if (value.length() >= 16) {
            value = value.substring(0, 16);
            isNum = pattern.matcher(value);
            if (isNum.matches()) {
                String[] sts = value.split("--");
                res = checkDateString(sts[0]);
                if (!res.isSuccess()) {
                    return res;
                }
                qjStart = (Date)res.getObj();

                res = checkDateString(sts[1]);
                if (!res.isSuccess()) {
                    return res;
                }
                qjEnd = (Date)res.getObj();


                if (isFirst) {
                    if (isQJ) {

                        if (qjStart.getTime() >= start.getTime()) {
                            return Result.ok();
                        }
                        return Result.fail("“" + value + "“中的起始年月需要在此条简历的开始时间之后！");
                    }

                    if (qjStart.getTime() >= lastStart.getTime()) {
                        return Result.ok();
                    }
                    return Result.fail("“" + value + "“中的起始年月需要在上条简历的开始时间之后！");
                }


                if (isQJ) {

                    if (qjStart.getTime() >= start.getTime() && qjEnd.getTime() <= end.getTime() && qjStart.getTime() <= qjEnd.getTime()) {
                        return Result.ok();
                    }
                    return Result.fail("“" + value + "“中的年月需要在此条简历的开始和结束时间之间！");
                }

                if (qjStart.getTime() >= lastStart.getTime() && qjEnd.getTime() <= end.getTime() && qjStart.getTime() <= qjEnd.getTime()) {
                    return Result.ok();
                }
                return Result.fail("“" + value + "“中的年月需要在上条简历的开始和这条简历的结束时间之间！");
            }



            value = value.substring(0, 7);
            isNum = pattern1.matcher(value);
            if (isNum.matches()) {
                res = checkDateString(value);
                if (!res.isSuccess()) {
                    return res;
                }
                qjStart = (Date)res.getObj();
                if (isLast) {
                    if (qjStart.getTime() >= start.getTime()) {
                        return Result.ok();
                    }
                    return Result.fail("“" + value + "“中的开始年月需要在这条简历的开始时间之后！");
                }

                if (qjStart.getTime() >= start.getTime() && qjStart.getTime() <= end.getTime()) {
                    return Result.ok();
                }
                return Result.fail("“" + value + "“中的年月需要在这条简历的开始和这条简历的结束时间之间！");
            }



            return Result.fail(oriValue + "中格式不对，应该是“年.月”格式的不是“年.月”的格式！");
        }

        return Result.ok();
    }
    public static Result checkDateString(String str) {
        if (str.indexOf(".") == -1) {
            return new Result(false, "该简历中”" + str + "”的日期格式不正确！");
        }
        try {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM");
            sd.setLenient(false);
            Date date = sd.parse(str);
            if (null == date) {
                return new Result(false, "该简历中”" + str + "”的日期格式不正确！");
            }
            return new Result(true, date);
        } catch (Exception e) {
            return new Result(false, "该简历中”" + str + "“的日期格式不正确！");
        }
    }





    private Result parse(String dateStr) {
        if (null != dateStr && StringUtils.isNotBlank(dateStr)) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");

                return Result.check(sdf.parse(dateStr));
            } catch (Exception e) {
                return Result.fail(dateStr + "不符合年.月格式！");
            }
        }
        return Result.ok();
    }






    public String getJianliFromListMap(List<Map<String, Object>> listmap) {
        StringBuffer sb = new StringBuffer();
        for (Map<String, Object> lom : listmap) {
            String key = StringUtils.getString(lom.get("key"));
            String value = StringUtils.getString(lom.get("value"));
            if (key.length() <= 9) {
                sb.append(key + "         ");
            } else {
                sb.append(key + "  ");
            }

            if (StringUtils.isNotBlank(value)) {
                value = value.replaceAll("\"", "“");
            }
            List<Integer> list = new ArrayList<>();
            list = getSpecialSignIndexArray(value, "（", 0, list);
            list = getSpecialSignIndexArray(value, "(", 0, list);
            Collections.sort(list);
        }
        return sb.toString();
    }






    public static String listToShowString(List<Map<String, Object>> list) {
        StringBuffer sb = new StringBuffer();
        int i = 0;
        for (Map<String, Object> map : list) {
            String key = StringUtils.getString(map.get("key"));
            String value = StringUtils.getString(map.get("value"));
            if (StringUtils.isBlank(key.trim()) && StringUtils.isBlank(value.trim())) {
                continue;
            }
            if (StringUtils.isBlank(key)) {
                sb.append("\n                  " + value);
            } else {
                sb.append(strToString(key) + "  " + value.replaceAll("<br/>", "\n                          ").replaceAll("<\br>", "\n                          "));
            }
            if (i < list.size() - 1) {
                sb.append("\n");
            }
            i++;
        }
        return sb.toString();
    }


    public static String strToString(String str) {
        str = str.replaceAll(" ", "");
        if (str.length() < 16) {
            int a = 16 - str.length();
            for (int i = 0; i < a; i++) {
                str = str + " ";
            }
        }
        return str;
    }

    public List<Map<String, String>> getA1701ListHB(String a1701) {
        if (StringUtils.isBlank(a1701)) {
            return new ArrayList<>();
        }

        String[] st = a1701.replaceAll("\n", "\r").replaceAll("\\(", "（").replaceAll("\\)", "）").split("\r");
        List<Map<String, String>> listMap = new ArrayList<>();
        String[] sts = null;
        List<Integer> listInt = null;
        for (int j = 0; j < st.length; j++) {
            String str = st[j];
            Map<String, String> map = new HashMap<>();
            String string = "";
            str = str.trim().replaceAll("&nbsp;", " ").replaceAll("　　　　", " ");
            sts = str.split(" ");
            if (sts.length > 0) {
                if (j == st.length - 1 && sts.length == 1 &&
                        ResumeUtil.isHaveString(sts[0])) {
                    map.put("key", "");
                    map.put("value", sts[0]);
                    listMap.add(map);

                    break;
                }
                map.put("key", sts[0]);
                if (sts.length > 1) {
                    for (int i = 1; i < sts.length; i++) {
                        String newStr = "";
                        if (StringUtils.isNotBlank(sts[i])) {
                            listInt = new ArrayList<>();
                            listInt = ResumeUtil.getSpecialSignIndexArray(sts[i], "（", 0, listInt);
                            listInt = ResumeUtil.getSpecialSignIndexArray(sts[i], "(", 0, listInt);
                            Collections.sort(listInt);
                            newStr = ResumeUtil.dealJianliSpecialPartToShow(sts[i], listInt);
                            string = string + newStr;
                        }
                    }


                    map.put("value", string);
                } else {
                    map.put("value", string);
                }
                listMap.add(map);
            }
        }

        return listMap;
    }

}
